import random
from django import http
import json

from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
import logging

logger = logging.getLogger('django')

class SMSCodeView(View):
    """短信验证码"""

    def get(self,request,mobile):

        redis_conn = get_redis_connection('verify_code')

        sms_code = '%06d' % random.randint(0, 999999)

        logger.info(sms_code)
        print('短信验证码:',sms_code)
        # 创建 Redis 管道
        pl = redis_conn.pipeline()

        # 将 Redis 请求添加到队列
        pl.setex('sms_%s' % mobile, 60, sms_code)
        pl.setex('send_flag_%s' % mobile, 60, 1)

        # 执行请求
        pl.execute()

        # # 7. 返回发送成功的响应

        return http.JsonResponse({'success': True,
                                  'message': "OK",
                                  "sms_code": sms_code})


